//
//  SendPostVC.m
//  sensen_ios
//
//  Created by pro on 16/3/3.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "SendPostVC.h"
#import "ZKTextImgReplaceHandle.h"
#import "FaceView.h" // 表情
#import "ForumSectionVC.h" //列表界面
@interface SendPostVC () <UITextViewDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, FaceViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
{
    UITextField *_titleTextField; // 标题
    UITextView *_contentTextView; // 内容
    NSMutableString *_contentText;
    
    UICollectionView *_collectionView; // 放图片的滑动视图
    NSMutableArray *_imgAry; // 图片数组

    UIButton *_faceButton; // 表情
    UIButton *_pictureButton; // 图片
    
    UIButton *_addButton; // 图片边上的用于点击添加的imgView
    UILabel *_notesLabel; // 标注视图，注释当前已经有几张图片，并告知还有几张可选
    
    FaceView *_faceView; // 表情
    NSMutableArray *_imIdAry;

}
@end

@implementation SendPostVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithWhite:0.92 alpha:1];
    self.title = @"发表帖子";
    _imIdAry = [[NSMutableArray alloc]initWithCapacity:5];
    [self createLeftBarButtonItemWithImagename:nil]; // 创建导航栏左侧返回
    [self createRightBarButtonItemWithTitle:@"发表"]; // 创建导航栏右侧发表
    
    [self _createViews]; // 创建视图

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main hideTabBar];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main showTabBar];
}


#pragma mark - 创建视图
- (void)_createViews {
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardDown)];
    [self.view addGestureRecognizer:tap];
    
    [self _createTitleTextField]; // 标题输入框
    [self _createContentTextView]; // 内容输入框
//    [self _createScrollView]; // 图片放置滑动视图
    [self _createCollectionView]; // 图片放置滑动视图
    [self _createNotesLabel]; // 标注视图
    [self _createFaceView]; // 表情
}
// 创建表情视图
- (void)_createFaceView {
    
    _faceView = [[FaceView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 216)];
    _faceView.top = SCREEN_HEIGHT - 64;
    _faceView.delegate = self;
    [self.view addSubview:_faceView];
    
    [_NOTIFICATION_CENTER addObserver:self selector:@selector(faceViewFrameChange:) name:FaceViewFrameChange object:nil];

}
// 标题输入框
- (void)_createTitleTextField {
    // 基底视图
    UIView *basalView = [[UIView alloc] init];
    basalView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
    basalView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:basalView];
    
    // 输入框
    _titleTextField = [[UITextField alloc] init];
    _titleTextField.frame = CGRectMake(10, 5, basalView.width - 10 * 2, basalView.height - 5 * 2);
    _titleTextField.placeholder = @"标题(必填)";
    [basalView addSubview:_titleTextField];
    
    // 线
    UIView *line = [[UIView alloc] init];
    line.frame = CGRectMake(0, 0, SCREEN_WIDTH, 1);
    line.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
    [basalView addSubview:line];
    line.bottom = basalView.height;
    
}
// 内容输入框
- (void)_createContentTextView {
    
    // 基底视图
    UIView *basalView = [[UIView alloc] init];
    basalView.backgroundColor = [UIColor whiteColor];
    basalView.frame = CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT * 0.4);
    [self.view addSubview:basalView];
    basalView.tag = 102;
    
    // 内容输入框
    _contentTextView = [[UITextView alloc] init];
    _contentTextView.frame = CGRectMake(5, 5, SCREEN_WIDTH - 5 * 2, basalView.height - 5 - 50);
    _contentTextView.backgroundColor = [UIColor whiteColor];
    _contentTextView.font = FONT(13);
    _contentTextView.delegate = self;
    _contentTextView.textColor = [UIColor darkGrayColor];
    [basalView addSubview:_contentTextView];
    
    // 线
    UIView *line = [[UIView alloc] init];
    line.frame = CGRectMake(0, 0, SCREEN_WIDTH, 1);
    line.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
    [basalView addSubview:line];
    line.top = _contentTextView.bottom;
    
    // 表情
    _faceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _faceButton.frame = CGRectMake(20, _contentTextView.bottom + (50 - 25) / 2.0, 25, 25);
    [_faceButton setImage:[UIImage imageNamed:@"论坛_发表帖子_表情"] forState:UIControlStateNormal];
    [_faceButton addTarget:self action:@selector(_faceTap:) forControlEvents:UIControlEventTouchUpInside];
    [basalView addSubview:_faceButton];
    
    // 图片
    _pictureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _pictureButton.frame = CGRectMake(_faceButton.right + 20, _faceButton.top, 25, 25);
    [_pictureButton setImage:[UIImage imageNamed:@"论坛_发表帖子_图片"] forState:UIControlStateNormal];
    [_pictureButton addTarget:self action:@selector(_pictureTap:) forControlEvents:UIControlEventTouchUpInside];
    [basalView addSubview:_pictureButton];
    
}
// 创建放置图片的滑动视图
- (void)_createCollectionView {
    
    // 初始化数据类
    _imgAry = [[NSMutableArray alloc] init];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat width = (SCREEN_WIDTH - 15 * 4) / 3;
    CGFloat height = width;
    layout.itemSize = CGSizeMake(width, height);
    layout.minimumInteritemSpacing = 15;
    layout.minimumLineSpacing = 15;
    layout.sectionInset = UIEdgeInsetsMake(0, 15, 0, 15);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    UIView *contentBasalView = [self.view viewWithTag:102];
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, contentBasalView.bottom + 20, SCREEN_WIDTH, height) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self.view addSubview:_collectionView];
    // 注册单元格
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"imgCell"];
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"btnCell"];


}
// 标注视图，注释当前已经有几张图片，并告知还有几张可选
- (void)_createNotesLabel {
    CGFloat x = 0;
    CGFloat y = _collectionView.bottom + 10;
    CGFloat width = SCREEN_WIDTH;
    CGFloat height = 20;
    _notesLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _notesLabel.font = FONT(15);
    _notesLabel.text = @"已选0张，还剩6张可选，多余三张可滑动查看";
    _notesLabel.textColor = [UIColor colorWithWhite:0.5 alpha:1];
    _notesLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_notesLabel];
}
#pragma mark - UICollectionView 代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _imgAry.count + 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat width, height;
    CGFloat margin = 15;
    width = (SCREEN_WIDTH - margin * 4) / 3;
    height = width;
    
    // 按钮单元格（添加图片）
    if (indexPath.row == _imgAry.count) {
        UICollectionViewCell *btnCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"btnCell" forIndexPath:indexPath];
        // 添加按钮
        UIButton *addbutton = [UIButton buttonWithType:UIButtonTypeCustom];
        addbutton.frame = CGRectMake(0, 0, width, height);
        [addbutton setImage:[UIImage imageNamed:@"论坛_添加图片"] forState:UIControlStateNormal];
        [addbutton addTarget:self action:@selector(_pictureTap:) forControlEvents:UIControlEventTouchUpInside];
        addbutton.layer.borderColor = ([UIColor colorWithRGBHex:0xbbbbbb]).CGColor;
        addbutton.layer.borderWidth = 0.5;
        [btnCell addSubview:addbutton];
        
        return btnCell;
    }
    // 图片单元格
    else {
        UICollectionViewCell *imgCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imgCell" forIndexPath:indexPath];
        if (imgCell == nil) {
            imgCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imgCell" forIndexPath:indexPath];
        }
        else
        {
            //删除cell的所有子视图
            while ([imgCell.subviews lastObject] != nil)
            {
                [(UIView*)[imgCell.subviews lastObject] removeFromSuperview];
            }
        }

        UIImageView *imgView = [[UIImageView alloc] init];
        imgView.userInteractionEnabled = YES;
        imgView.frame = CGRectMake(0, 0, width, height);
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imgView.image = _imgAry[indexPath.row];
        [imgCell addSubview:imgView];
        
        // 删除按钮
        UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        deleteBtn.frame = CGRectMake(0, 0, 20, 20);
        [deleteBtn setBackgroundImage:[UIImage imageNamed:@"论坛_删除图片"] forState:UIControlStateNormal];
        [deleteBtn addTarget:self action:@selector(_deleteImgAction:) forControlEvents:UIControlEventTouchUpInside];
        [imgView addSubview:deleteBtn];
        deleteBtn.center = CGPointMake(imgView.width - 15, 15);
        
        return imgCell;
    }
    
}
- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender {

}
#pragma mark - 点击事件
// 删除图片
- (void)_deleteImgAction:(UIButton *)button {
    // 找到对应的单元格来获得数组中图片的索引，然后删除图片，重载UICollectionView
    UIImageView *imgView = (UIImageView *)button.superview;
    UICollectionViewCell *imgCell = (UICollectionViewCell *)imgView.superview;
    NSIndexPath *indexPath = [_collectionView indexPathForCell:imgCell];
    if (button == nil) {
        [_imgAry removeLastObject];
    }else{
        [_imgAry removeObjectAtIndex:indexPath.row];
    }
    [_collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    
    if ((_imIdAry.count != indexPath.row) && button != nil) {
        // 删除图片id
        [_imIdAry removeObjectAtIndex:indexPath.row];
    }
    
    // 刷新注释文本
    _notesLabel.text = [NSString stringWithFormat:@"已选%li张，还剩%li张可选，多余三张可滑动查看", (unsigned long)_imgAry.count,6 - _imgAry.count];
}
// 添加图片
- (void)_addImgAction:(UIImage *)image {
    
    if (_imgAry.count == 6) {
        [SVProgressHUD showErrorWithStatus:@"您最多可上传6张图片" withDuration:2];
        return;
    } else {
        [_imgAry addObject:image];
        [_collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
        // 刷新注释文本
        _notesLabel.text = [NSString stringWithFormat:@"已选%li张，还剩%li张可选，多余三张可滑动查看", (unsigned long)_imgAry.count,6 - _imgAry.count];
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_imgAry.count inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
}
// 发表
- (void)rightAction:(UIButton *)button {
    
    if (_titleTextField.text.length <= 0 || _contentTextView.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请填写完整" withDuration:1.5];
        return;
    }
    [SVProgressHUD showWithStatus:@"请稍等..." maskType:SVProgressHUDMaskTypeBlack];
    UserModel *user = [CommonCache getUserInfo];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
     NSString *typeid = @"0";
    [params setObject:typeid forKey:@"typeid"];
    [params setObject:_fid forKey:@"fid"];
    [params setObject:user.nickname forKey:@"author"];
    [params setObject:user.uid forKey:@"author_id"];
    [params setObject:_contentTextView.text forKey:@"message"];
    [params setObject:_titleTextField.text forKey:@"subject"];
    if (_imIdAry.count != 0) {
        NSString *attid = @"";
        for (NSString *imId in _imIdAry) {
            attid = [attid stringByAppendingString:[NSString stringWithFormat:@"%@,",imId]];
        }
        NSString *attids = [attid substringToIndex:attid.length - 1];
        [params setObject:attids forKey:@"attachments"];
    }
        [BoyeHttpClient post:@"BY_ForumThread_add" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
            
            [_collectionView reloadData];
            [self.delegate refreshVC];
//            [self.navigationController popViewControllerAnimated:YES];
            [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@",(NSString *)result] withDuration:1];
            [self performSelector:@selector(_pop) withObject:self afterDelay:1];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"发表失败请重试,%@",error.domain] withDuration:1];
        }];
}

-(void)_pop{
    [self.navigationController popViewControllerAnimated:YES];
}
// 表情
- (void)_faceTap:(UIButton *)button {
    [_faceView show];
}
// 图片
- (void)_pictureTap:(UIButton *)button {
    
    if (_imgAry.count == 6) {
        [SVProgressHUD showErrorWithStatus:@"您最多可上传6张图片" withDuration:2];
        return;
    }
    // 适配版本iOS8.0以上
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
        // 创建ActionSheet
        NSString *albumButtonTitle = @"从相册中选择";
        NSString *cameraButtonTitle = @"拍照";
        NSString *cancelButtonTitle = @"取消";
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        // 添加点击动作
        // 取消
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:nil];
        // 相册中
        UIAlertAction *albumAction = [UIAlertAction actionWithTitle:albumButtonTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            
            [self _choosePhotoFromAlbum];
        }];
        // 拍照
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:cameraButtonTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self _getphotoFromCamera];
        }];
        
        // Add the actions.
        [alertController addAction:cancelAction];
        [alertController addAction:albumAction];
        [alertController addAction:cameraAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
    // 适配版本8.0以下
    else {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册中选择",@"拍照", nil];
        [sheet showInView:self.view];
    }
    
}



#pragma mark - 表情点击代理事件
- (void)faceViewDidChooseFace:(NSString *)face {
    
    [_contentTextView setText:[NSString stringWithFormat:@"%@%@", _contentTextView.text, face]];
    
}


#pragma mark - UITextView 代理
- (void)textViewDidChange:(UITextView *)textView {
    
//    _contentText = [textView.text mutableCopy];
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    [_faceView hide];
    return YES;
}



#pragma mark - 键盘事件
// 表情视图位置改变方法
//TODO: 这里不和该控制器的视图交互，所以这个方法可以没有，但是先写着。
- (void)faceViewFrameChange:(NSNotification *)notification {
    
    [_APP_KEYWINDOW endEditing:YES]; // 隐藏键盘
    
    [UIView animateWithDuration:0.25 animations:^{
        NSDictionary *info = notification.userInfo;
        NSString *frameStr = info[FaceViewFrameEndInfo];
        CGRect frame = CGRectFromString(frameStr);
        // 表情视图上升
        if (frame.origin.y < SCREEN_HEIGHT - 64) {

        }
        // 表情视图下降
        else {

        }
    }];
}
// 重写键盘下降事件（外加一个隐藏表情）
- (void)keyboardDown {
    [super keyboardDown];
    
    [_faceView hide];
}



#pragma mark - 头像图片选择相关操作
// 从相册中选择照片
- (void)_choosePhotoFromAlbum
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        [SVProgressHUD showErrorWithStatus:@"相册不可用！" withDuration:1];
        return;
    }
    [self _changeToPickerController:sourceType];
}

// 通过拍照获取照片
- (void)_getphotoFromCamera
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        [SVProgressHUD showErrorWithStatus:@"相机不可用！" withDuration:1];
        return;
    }
    [self _changeToPickerController:sourceType];
}

// 创建并跳转到图片获取界面
- (void)_changeToPickerController:(UIImagePickerControllerSourceType)sourceType
{
    //创建图片拾取界面
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    //设置可编辑
    pickerController.sourceType = sourceType;
    if (pickerController.sourceType == UIImagePickerControllerSourceTypeCamera) {
        pickerController.allowsEditing = YES;
    }
    pickerController.title = @"图片选择";
    [pickerController.navigationBar setTintColor:[UIColor darkGrayColor]];
    [self presentViewController:pickerController animated:YES completion:nil];
}

//UIImagePickerController代理方法，选取图片之后处理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *showImage;
    UIImage *editedImage = (UIImage *)[info objectForKey:UIImagePickerControllerEditedImage];
    UIImage *originalImage = (UIImage *)[info objectForKey:UIImagePickerControllerOriginalImage];

    if (editedImage) {
        // 保存到相册
        UIImageWriteToSavedPhotosAlbum(editedImage, nil, nil, nil);
        // 设置图片
        showImage = editedImage; // 相册图片可截取，一直是正方形的
        originalImage = editedImage;
    }
    else if (originalImage) {
        // 设置图片
        showImage = [originalImage getCenterImage];
    }
    
    // 图片添加
    [self _addImgAction:showImage];
    
    NSData *imageData = UIImageJPEGRepresentation(originalImage, 1);
    CGFloat length_kb = [imageData length] / 4096.0;
    // 压缩文件
    if (length_kb >= 500 ) {
//        NSLog(@"=====%lf",length_kb);
        originalImage = [UIImage imageWithData:UIImageJPEGRepresentation(originalImage, 0)];
        imageData = UIImageJPEGRepresentation(originalImage, 1);
        length_kb = [imageData length] / 4096.0;
//        NSLog(@"%lf",length_kb);
    }
//    NSLog(@"文件大小:%lf", length_kb);
    if (length_kb >= 500) {
        originalImage = [self scaleToSize:CGSizeMake(500, 500) :originalImage];
    }
    
    // 返回“个人”界面
    [self dismissViewControllerAnimated:YES completion:^{
         //上传图片
        
        [BoyeHttpClient uploadImage:originalImage type:@"bbs" success:^(NSDictionary *dataDic) {
            NSLog(@"成功回调:%@", dataDic);
            NSString *imageId  =  dataDic[@"id"];
            [_imIdAry addObject:imageId];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [self _deleteImgAction:nil];
        }];
    }];
 
}


//裁剪图片
-(UIImage*)scaleToSize:(CGSize)size :(UIImage *)image
{
    CGFloat width = CGImageGetWidth(image.CGImage);
    CGFloat height = CGImageGetHeight(image.CGImage);
    
    float verticalRadio = size.height*1.0/height;
    float horizontalRadio = size.width*1.0/width;
    
    float radio = 1;
    if(verticalRadio > 1 && horizontalRadio > 1)
    {
        radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio;
    }
    else
    {
        radio = verticalRadio > horizontalRadio ? verticalRadio : horizontalRadio;
    }
    
    width = width*radio;
    height = height*radio;
    
    int xPos = (size.width - width)/2;
    int yPos = (size.height-height)/2;
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(xPos, yPos, width, height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}


#pragma mark - UIActionSheet代理方法（适配iOS8.0以下时使用）
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    // 选择照片
    // 从相册中选择
    if (buttonIndex == 0) {
        [self _choosePhotoFromAlbum];
    }
    // 通过拍照获取
    else if (buttonIndex == 1) {
        [self _getphotoFromCamera];
    }
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
